package com.application.Activity;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;


public class frmChatPeerActivity extends Activity implements OnClickListener, OnKeyListener {
	public static int CODE_CHATPEER = 1001;
	public static String IP_CHAT_PEER = "IP_CHAT_PEER";
	public static String USERNAME = "USERNAME";

	private static final int SENDFILE = Menu.FIRST + 7;
	EditText _edtmessage;
	static private ArrayList<String> _messages = new ArrayList<String>();
	static MyChatPeerAdapter _myAdapter;
	Button _btnSend;
	static ListView _lvcontentchat;

	// ===========
	// truyen du lieu qua form:
	public static String IPMyFriend;
	public static String UserNameMyFriend;
	// =============
	public static String _IPFriend;
	String _fullNameFriend = "TRUC";
	public static String _userNameFriend;
	public static String _FriendChatting;
	private static String _pathContentChat;
	// ==============
	public static Runnable closeMyForm;
	static Context _cont;
	private TextView _txtusername;
	private TextView _txtfullname;
	String _textSend = "";
	public static Runnable _runUpdateMsg;
	// static Handler _handler = new Handler();
	String _acc = "";
	String _mess = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.layout_chat_peer);

		Log.d("Phu", "vao oncreate chat peer");
		_cont = this;
		_edtmessage = (EditText) findViewById(R.id.chatpeer_txtmessage);
		_btnSend = (Button) findViewById(R.id.chatpeer_btnSend);
		_txtusername = (TextView) findViewById(R.id.chatpeer_txtusername);
		_txtfullname = (TextView) findViewById(R.id.chatpeer_txtfullname);
		_lvcontentchat = (ListView) findViewById(R.id.chatpeer_lvcontent);
		_lvcontentchat.setDividerHeight(0);
		Log.d("Phu", "~~~~~~~~~~~My username =" + NetworkController._peer.getAccount().get_Username());
		Log.d("Phu", "~~~~~~~~~~~My ip =" + NetworkController._peer.getAddressPeer());
		NetworkController.init_runnableUpdateMsg();
		if (IPMyFriend == null && UserNameMyFriend == null) {
			Log.d("Phu", ">>>>>>Co intent");
			Log.d("Phu", ">>>>>>>username intent " + getIntent().getExtras().getString(USERNAME));
			Log.d("Phu", ">>>>>>>ip intent " + getIntent().getExtras().getString(IP_CHAT_PEER));
			_IPFriend = getIntent().getExtras().getString(IP_CHAT_PEER);
			_userNameFriend = getIntent().getExtras().getString(USERNAME);
			_FriendChatting = _userNameFriend;
		} else {
			Log.d("Phu", "Co tham so truyen sang");
			Log.d("Phu", "~~~~~~~~~~~ username =" + UserNameMyFriend);
			Log.d("Phu", "~~~~~~~~~~~ ip =" + IPMyFriend);
			_IPFriend = IPMyFriend;
			_userNameFriend = UserNameMyFriend;
			_FriendChatting = _userNameFriend;
		}
		closeMyForm = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				finishForm();
			}
		};
		_runUpdateMsg = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				updateMessage(_IPFriend, _userNameFriend);
			}
		};
		// lay DC IP duoc goi qua tu form Profile
		// _userNameFriend = getIntent().getExtras().getString("username");
		// _fullNameFriend = getIntent().getExtras().getString("fullname");
		// _IPFriend = getIntent().getExtras().getString("IP");
		Log.d("Phu", "username chat peer " + _userNameFriend);
		Log.d("Phu", "ip chat peer " + _IPFriend);
		_txtfullname.setText(_IPFriend);
		_txtusername.setText(_userNameFriend);

		_pathContentChat = ReadWriteFileController.DIRECTORYCHATPEER + "Peer_" + _userNameFriend + ".txt";
		// ---------xac dinh editext enter khi chat------------------
		_edtmessage.setOnKeyListener(this);
		setListAdapter();
		// thiết lập sự kiện nhấn nút Send và bấm ENTER
		_btnSend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sendMessage();
			}
		});
	}

	void finishForm() {
		finish();
	}

	public static void setPathContentChat(String userName) {
		_pathContentChat = ReadWriteFileController.DIRECTORYCHATPEER + "Peer_" + userName + ".txt";
	}

	public static void setListAdapter() {
		Log.d("Phu", "set list adapter");
		_messages.clear();
		_messages = ReadWriteFileController.ReadTXT(_pathContentChat);
		_myAdapter = new MyChatPeerAdapter(_cont, R.layout.row_chatpeer, _messages);
		_lvcontentchat.setAdapter(_myAdapter);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// ReadWriteFileController.deleteFile(_pathContentChat);

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.d("Phu", "vao onstart chat peer");
		ActivityController.setPeerActivity(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// ShowSubjectList();
		Log.d("Phu", "vao resume");
		ActivityController.setPeerActivity(this);
	}

	@Override
	public void onPause(){
		super.onPause();
		ActivityController.setPeerActivity(this);
	}
	/**
	 * ham set lai noi dung message chat tren list
	 * 
	 * @param acc
	 * @param mess
	 */
	public static void updateMessage(String userName, String ip) {
		_userNameFriend = userName;
		_IPFriend = ip;
		_messages = new ArrayList<String>();
		setListAdapter();
		// _handler.post(_runUpdateMsg);
	}

	public static void updateMessage() {
		_messages = new ArrayList<String>();
		setListAdapter();
		Log.d("Phu", "het update message ");
	}

	/**
	 * khi xoay man hinh thi noi dung tren list khong bien mat
	 */
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	/**
	 * goi khi send messge di, click send
	 * 
	 * @throws IOException
	 */
	private void sendMessage() {
		// username cua minh+tin nhan+ip cua minh
		String text = _edtmessage.getText().toString();
		String textSend = NetworkController._peer.getAccount().get_Username() + "/" + text + "/"
				+ NetworkController._peer.getAddressPeer();
		Log.d("Phu", "noi dung : " + textSend);
		// set lai message show len list
		if (!text.equals("")) {
			// --------ghi noi dung chat xuong-------------
			try {
				ReadWriteFileController.writeTXTPath(ReadWriteFileController.DIRECTORYCHATPEER + "Peer_"
						+ _userNameFriend + ".txt", "Tôi: " + text);
			} catch (IOException e) {
				
				e.printStackTrace();
			}
			Log.d("Phu", "setlist adapter");
			setListAdapter();
			Log.d("Phu", "setlist adapter hoan tat");
			// cập nhật lại conversation
			Log.d("Phu", "keychat: " + _userNameFriend + " text: " + text + "type: " + 1 + "IP: " + _IPFriend
					+ "fullName: " + _fullNameFriend);
			// -cu-
			// NetworkController.UpdateMessageInConversation(_userNameFriend,
			// text, _IPFriend);
			// NetworkController.UpdateMessageInConversation(_userNameFriend,
			// text, 1, _IPFriend, "abcd");

			// thuc hien gui thong diep den ban chat
			NetworkController.SendChatMessagePeer(new Address(_IPFriend), textSend);
			_edtmessage.setText("");
		}
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_ENTER:
			sendMessage();
			return true;
		case KeyEvent.KEYCODE_BACK:
			_FriendChatting = null;
			finish();
		}
		return false;
	}

	private static class MyChatPeerAdapter extends ArrayAdapter<String> {
		private Context _context;
		// private LayoutInflater mInflater;
		private int _resource;
		private Resources mResources;
		private ArrayList<String> mMessages;

		public MyChatPeerAdapter(Context context, int resource, ArrayList<String> arrmess) {
			// mInflater = LayoutInflater.from(context);
			// mResources = context.getResources();
			super(context, resource, arrmess);
			_context = context;
			_resource = resource;
			mMessages = arrmess;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mMessages.size();
		}

		@Override
		public long getItemId(int pos) {
			// TODO Auto-generated method stub
			return pos;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final String messView = mMessages.get(position);
			if (convertView == null) {
				LayoutInflater lInflater = (LayoutInflater) this.getContext().getSystemService(
						Context.LAYOUT_INFLATER_SERVICE);
				convertView = lInflater.inflate(R.layout.row_chatpeer, null, true);
			}
			if (messView != null) {
				TextView txtContent = (TextView) convertView.findViewById(R.id.row_txtcontent);
				LinearLayout llo = (LinearLayout) convertView.findViewById(R.id.row_lloreceivefile);
				TextView txtFileName = (TextView) convertView.findViewById(R.id.row_txtfilename);
				TextView txtOk = (TextView) convertView.findViewById(R.id.row_txtok);
				TextView txtCancel = (TextView) convertView.findViewById(R.id.row_txtcancel);

				String[] sTemp = messView.split(":");
				String mess = getMessage(sTemp);
				String firsttext = sTemp[0];
				// -----------------co file goi den------------
				if (firsttext.equals("##file##")) {
					txtContent.setVisibility(View.GONE);
					llo.setVisibility(View.VISIBLE);
					txtCancel.setVisibility(View.VISIBLE);
					txtFileName.setVisibility(View.VISIBLE);
					txtOk.setVisibility(View.VISIBLE);
					// nhan duoc tap tin dinh kem
					String[] content = mess.split("##");
					final String t = content[2];
					final String address = content[3];
					final String port = content[4];
					txtFileName.setText(content[0] + content[1] + content[2]);

					// set su kien khi dong y nhan file
					txtOk.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							Toast toast = Toast.makeText(ActivityController.getPeerActivity(), "Ok", Toast.LENGTH_SHORT);
							toast.show();
							Intent intent = new Intent(ActivityController.getPeerActivity().getBaseContext(),
									FrmSelectFile.class);
							FrmSelectFile.setFileName(t);
							FrmSelectFile.set_address(address);
							FrmSelectFile.set_port(port);
							FrmSelectFile.set_lineToRemove(messView);
							ActivityController.getPeerActivity().startActivityForResult(intent, 1);
						}
					});
					// set su kien khi khong dong y nhan file
					txtCancel.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							Toast toast = Toast.makeText(ActivityController.getPeerActivity(), "Cancel",
									Toast.LENGTH_SHORT);
							toast.show();

						}
					});
				}
				// -----------co thong bao-------------
				else if (firsttext.equals("##notify##")) {
					txtContent.setVisibility(View.VISIBLE);
					llo.setVisibility(View.GONE);
					txtCancel.setVisibility(View.GONE);
					txtFileName.setVisibility(View.GONE);
					txtOk.setVisibility(View.GONE);
					txtContent.setText(mess);
				}
				// -------------tin nhan chat---------------
				else {
					txtContent.setVisibility(View.VISIBLE);
					llo.setVisibility(View.GONE);
					txtCancel.setVisibility(View.GONE);
					txtFileName.setVisibility(View.GONE);
					txtOk.setVisibility(View.GONE);
					String fullName = sTemp[0];

					if (fullName.equals("Tôi")) {
						// txtUserName.setTextColor(Color.GRAY);
						txtContent.setText(Html.fromHtml("<b><font color='#696969' size='14'>" + fullName + ": "
								+ "</font></b>" + "<font color='black' size='20'>" + mess + "</font>"));
					} else {
						// txtUserName.setTextColor(Color.BLUE);
						txtContent.setText(Html.fromHtml("<b><font color='blue' size='14'>" + fullName + ": "
								+ "</font></b>" + "<font color='black' size='20'>" + mess + "</font>"));
					}
				}
			}

			return convertView;
		}

		private String getMessage(String[] temp) {
			String result = "";
			// i chay tu 2 đe lay ra message
			for (int i = 1; i < temp.length; i++) {
				if (i == temp.length - 1) {
					result = result + temp[i];
				} else {
					result = result + temp[i] + ":";
				}
			}
			return result;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(Menu.NONE, SENDFILE, Menu.NONE, "Gửi dữ liệu").setAlphabeticShortcut('h');
		return (super.onCreateOptionsMenu(menu));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case SENDFILE:
			Intent intent = new Intent(this, FrmSelectFile.class);
			intent.putExtra(FrmSelectFile.START_PATH, "/sdcard");
			this.startActivityForResult(intent, 1);
			// startActivity(new Intent(this, FrmSelectFile.class));
			return (true);
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public synchronized void onActivityResult(final int requestCode, int resultCode, final Intent data) {
		Log.d("Phu", "onActivityResult");

		if (resultCode == CODE_CHATPEER) {
			_IPFriend = data.getStringExtra(IP_CHAT_PEER);
			_userNameFriend = data.getStringExtra(USERNAME);
			// if (ipFriend != null) {
			// frmChatPeerActivity.myFriend = new Address(ipFriend);
			// NetworkController.ShowChatPeer();
			// }
		}
		// if (resultCode == Activity.RESULT_OK) {
		//
		// String filePath = data.getStringExtra(FrmSelectFile.RESULT_PATH);
		// String type = data.getStringExtra(FrmSelectFile.RESULT_TYPE);
		// String address = data.getStringExtra(FrmSelectFile.RESULT_ADDRESS);
		// String port = data.getStringExtra(FrmSelectFile.RESULT_PORT);
		// String lineToRemove =
		// data.getStringExtra(FrmSelectFile.RESULT_LINETOREMOVE);
		// Log.d("Phu", "filepath: " + filePath);
		// if (type.equals("1"))// luu file
		// {
		// Log.d("Phu", "save file");
		// ThreadReceiveFile thread = new ThreadReceiveFile();
		// thread.setPathChatFile(ReadWriteFileController.DIRECTORYCHATPEER +
		// "Peer_" + _userNameFriend
		// + "_Content.txt");
		// String[] temp = filePath.split("/");
		// thread.setfName(temp[temp.length - 1]);
		// thread.SetReceive(filePath, address, Integer.valueOf(port));
		// thread.setLineToRemove(lineToRemove);
		// thread.start();
		// } else if (type.equals("2"))// send file
		// {
		// Log.d("Phu", "send file");
		// ArrayList<Address> arrDSGourp = new ArrayList<Address>();
		// arrDSGourp.add(new Address(_IPFriend));
		// ThreadSendFile thread = new ThreadSendFile();
		// thread.setSendFile(filePath, NetworkController.get_userName(),
		// NetworkController.PORT_NUMBER_CURRENT++,
		// "canhan", arrDSGourp);
		// thread.start();
		// }
		//
		// } else if (resultCode == Activity.RESULT_CANCELED) {
		// Log.d("Phu", "file not selected");
		// }

	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		sendMessage();
	}

	// ham nay la cai file lam dau tien cua chat rieng==TRUC
	void abc() {
		// public class frmChatPeerActivity extends Activity {
		//
		// public static ArrayList<String> arrMessage;
		// Button btnSend;
		// EditText txtChat;
		// ListView lvContent;
		// String noiDungChat;
		// String contentChatFinal;
		// public static Address myFriend;
		// public static Runnable showMessageChat;
		// @Override
		// public void onCreate(Bundle savedInstanceState) {
		// super.onCreate(savedInstanceState);
		// setContentView(R.layout.layout_chat_peer);
		// lvContent=(ListView)findViewById(R.id.lvConversation);
		// arrMessage=new ArrayList<String>();
		// txtChat=(EditText)findViewById(R.id.txtNoiDungTinNhan);
		//
		// showMessageChat=new Runnable() {
		//
		// @Override
		// public void run() {
		// // TODO Auto-generated method stub
		// fillListView();
		// }
		// };
		//
		// btnSend=(Button)findViewById(R.id.btnGuiTinNhan);
		// btnSend.setOnClickListener(new View.OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		//
		// Quyen myRule=NetworkController._peer.getAccount().getRuleById(7);
		// if(myRule!=null&&myRule.getSend()){
		// noiDungChat=txtChat.getText().toString();
		// contentChatFinal=NetworkController._peer.getAccount().get_Username()+" : "+noiDungChat;
		// arrMessage.add(contentChatFinal);
		// NetworkController.GuiTinNhanChat(myFriend, contentChatFinal);
		// fillListView();
		// }else
		// {
		// Log.d("Phu","ko dc quyen gui tin nhan chat");
		// NetworkController.ShowMessageNotice(Protocol.NON_RULE_MESSAGE);
		// }
		//
		// }
		// });
		// }
		// private void fillListView() {
		//
		// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
		// android.R.layout.simple_list_item_1, arrMessage);
		// lvContent.setAdapter(adapter);
		// }
		//
	}
}